<?php

require_once '../../includes/includes.php';

if(isset($_POST['upload'])) {
    
    $uploads_dir = '../../albums/';
    $allowedExts = array("gif", "jpeg", "jpg", "png");
    $allowedMimeTypes = array("image/gif", "image/jpeg", "image/jpg", "image/png");
    $album = $_POST['album'];
    $album_id = $_POST['album_id'];
    
    $files = rearrange($_FILES['file']);
    
    foreach($files as $file) {
        
        $pathinfo = pathinfo($file["name"]);
        $extension = $pathinfo['extension'];
        
        
        if(in_array($file['type'], $allowedMimeTypes) && in_array($extension, $allowedExts)) {
            
            if($file['error'] !== 0) {
                continue;
            }
            
            if(file_exists(ALBUM_PATH . $album . '/' . $file['name'])) {
                continue;
            }
            
            $res = move_uploaded_file($file['tmp_name'], $uploads_dir . $album . '/' . $file['name']);
            
            $data = array(
              'source' => $file['name'],  
              'title' => $file['name'],  
              'album_id' => $album_id,  
            );
            
            $db->insert('photographs', $data);
            
        }
        
    }
    
    header('Location: ' . $_SERVER['HTTP_REFERER']);
    
}